﻿CREATE PROCEDURE [dbo].[kp_DangKyKDKetThucDuyetHS]
	@Stt_Rec nvarchar(12),
	@Ma_Tt int,
	@NextMa_Tt int,	
	@Ly_Do nvarchar(512),
	@User0 nvarchar(23),
	@Client0 nvarchar(47)
AS
BEGIN
	Declare @Ma_Tt_Ht int,@Ghi_Chu_Ht nvarchar(512),@Ma_HS int
	Select @Ma_Tt_Ht=Ma_Tt,@Ghi_Chu_Ht=Ghi_Chu,@Ma_HS=Ma_Hs from tblDangKyKD where Stt_Rec=@Stt_Rec
		AND Ma_Tt=@Ma_Tt
	if @Ma_Tt_Ht is not null
	begin
		Insert Into [tblNhatKyHs]([Stt_Rec],[Ma_Tt_Cu],[Ma_Tt],[Ghi_Chu],[User0],[Date0],[Client0])
		VALUES(@Stt_Rec,@Ma_Tt_Ht,@NextMa_Tt,@Ly_Do,@User0,getdate(),@Client0);
		
		Update tblDangKyKD set Ht=0 where Ma_Hs=@Ma_Hs and Stt_Rec <> @Stt_Rec
		
		Update tblDangKyKD set Ma_Tt=@NextMa_Tt,Ghi_Chu=@Ly_Do,Ht=1 Where Stt_Rec=@Stt_Rec
		AND Ma_Tt=@Ma_Tt
		
		RETURN 0;
	end
	ELSE
		RETURN -1;
END